package middleware

import (
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/spf13/viper"
)

func GenerateOrderNumber(tag string, monitorType string, filePath string) string {

	today := time.Now().Format("20060102") // 获取当前日期

	count, _ := os.ReadFile(filePath) // 读取计数器的值
	counter, _ := strconv.Atoi(strings.TrimSpace(string(count)))
	fmt.Println(counter)

	date, _ := os.ReadFile(viper.GetString("document_path") + "/countvar/date") // 读取上一次的时间
	prevDate := string(date)

	if counter > 1 && today != prevDate { // 如果是第二天，则将计数器重置为1
		counter = 1
	}

	prevDate = today // 存储旧的日期

	counterStrFourBit := fmt.Sprintf("%04d", counter) // 将计数器格式化为四位数
	orderNumber := "VPKA-" + strings.ToUpper(tag) + "-" + strings.ToUpper(monitorType) + "-" + today + "-" + counterStrFourBit
	counter++

	counterStr := strconv.Itoa(counter) // 将计数器的值写入文件

	_ = os.WriteFile(filePath, []byte(counterStr), 0644) // 将计数器的值写入文件

	_ = os.WriteFile(viper.GetString("document_path")+"/countvar/date", []byte(prevDate), 0644) // 将旧的日期写入文件

	return orderNumber
}
